import { Toast } from "vant";
import Cookies from "js-cookie";
import { COOKIE_TOKEN, COOKIE_USER } from "~/common";
export default ({ store, app }, inject) => {
  inject("Toast", obj => Toast(obj));

  // 获取 cookie
  inject("getCookie", name => {
    try {
      return JSON.parse(Cookies.get(name) || "null");
    } catch (error) {
      return null;
    }
  });
  // 设置 cookie
  inject("setCookie", (name, val) => {
    const value = JSON.stringify(val);
    Cookies.set(name, value, { expires: 30 });
  });
  // 删除 cookie
  inject("rmCookie", (...args) => {
    args.forEach(key => {
      Cookies.remove(key);
    });
  });

  // 获取 本地存储数据
  inject("getStorageData", (key, isLocal) => {
    try {
      const storage = isLocal ? window.localStorage : window.sessionStorage;
      return JSON.parse(storage.getItem(key));
    } catch (error) {
      console.log(error);
      return null;
    }
  });
  // 设置本地存储
  inject("setStorageData", (isLocal, key, data) => {
    const storage = isLocal ? window.localStorage : window.sessionStorage;
    const d = JSON.stringify(data);
    storage.setItem(key, d);
  });
  // 删除本地存储
  inject("rmStorageData", (isLocal, ...args) => {
    const storage = isLocal ? window.localStorage : window.sessionStorage;
    args.forEach(key => {
      storage.removeItem(key);
    });
  });
  // 保持用户信息
  inject("saveUserInfo", (userInfo, token) => {
    store.commit("setUser", userInfo);
    store.commit("setToken", token);
    app.$setCookie(COOKIE_TOKEN, token);
    app.$setCookie(COOKIE_USER, userInfo);
    app.$setStorageData(true, COOKIE_TOKEN, token);
    app.$setStorageData(true, COOKIE_USER, userInfo);
  });
  // 格式化 cookie
  inject("formatCookie", str => {
    if (!str) {
      return null;
    }
    str = decodeURIComponent(str);
    return str.split(";").reduce((a, c) => {
      c = c.split("=");
      a[c[0].replace(/\s/g, "")] = c[1];
      return a;
    }, {});
  });

  // loading
  inject("helperLoadding", (msg = "加载中...") =>
    Toast.loading({
      message: msg,
      forbidClick: true
    })
  );
};
